<template>
  <div class="chart-settings-container">
    <a-form layout="vertical">
      <!-- 基本设置 -->
      <a-form-item label="图表标题">
        <a-input v-model:value="localOptions.title.text" placeholder="请输入图表标题" @change="emitUpdate" />
      </a-form-item>
      
      <!-- 词云设置 -->
      <a-divider>词云设置</a-divider>
      
      <a-form-item label="最小字号">
        <a-input-number 
          v-model:value="localOptions.series[0].textStyle.fontSize[0]" 
          :min="8" 
          :max="60" 
          style="width: 100%"
          @change="emitUpdate" 
        />
      </a-form-item>
      
      <a-form-item label="最大字号">
        <a-input-number 
          v-model:value="localOptions.series[0].textStyle.fontSize[1]" 
          :min="20" 
          :max="120" 
          style="width: 100%"
          @change="emitUpdate" 
        />
      </a-form-item>
      
      <a-form-item label="词云形状">
        <a-radio-group v-model:value="cloudShape" @change="updateCloudShape">
          <a-radio-button value="circle">圆形</a-radio-button>
          <a-radio-button value="cardioid">心形</a-radio-button>
          <a-radio-button value="diamond">菱形</a-radio-button>
          <a-radio-button value="triangle">三角形</a-radio-button>
          <a-radio-button value="pentagon">五边形</a-radio-button>
        </a-radio-group>
      </a-form-item>
      
      <a-form-item label="字体旋转">
        <a-switch v-model:checked="rotationEnabled" @change="updateRotation" />
      </a-form-item>
      
      <template v-if="rotationEnabled">
        <a-form-item label="旋转角度范围">
          <a-slider
            range
            v-model:value="rotationRange"
            :min="-90"
            :max="90"
            @change="updateRotationRange"
          />
        </a-form-item>
      </template>
      
      <a-form-item label="颜色方案">
        <a-select v-model:value="colorScheme" style="width: 100%" @change="updateColorScheme">
          <a-select-option value="category">分类色系</a-select-option>
          <a-select-option value="random">随机色系</a-select-option>
          <a-select-option value="gradient">渐变色系</a-select-option>
        </a-select>
      </a-form-item>
      
      <template v-if="colorScheme === 'gradient'">
        <a-form-item label="起始颜色">
          <a-input 
            v-model:value="startColor" 
            type="color"
            style="width: 100px" 
            @change="updateGradientColors" 
          />
        </a-form-item>
        
        <a-form-item label="结束颜色">
          <a-input 
            v-model:value="endColor" 
            type="color"
            style="width: 100px" 
            @change="updateGradientColors" 
          />
        </a-form-item>
      </template>
      
      <!-- 数据设置 -->
      <a-divider>数据设置</a-divider>
      
      <div v-for="(item, index) in wordCloudData" :key="index" class="word-item">
        <a-row :gutter="8">
          <a-col :span="10">
            <a-form-item label="词语">
              <a-input v-model:value="item.name" @change="updateWordCloudData" />
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item label="权重">
              <a-input-number 
                v-model:value="item.value" 
                :min="1" 
                style="width: 100%"
                @change="updateWordCloudData" 
              />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label=" " class="delete-btn-container">
              <a-button 
                type="primary" 
                danger 
                @click="removeWord(index)"
                shape="circle"
              >
                <delete-outlined />
              </a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </div>
      
      <a-button type="dashed" block @click="addWord" style="margin-top: 16px">
        <plus-outlined /> 添加词语
      </a-button>
      
      <!-- 数据批量导入 -->
      <a-divider>批量导入</a-divider>
      
      <a-form-item label="格式: 词语,权重 (每行一个)">
        <a-textarea 
          v-model:value="batchWordsText" 
          :rows="6" 
          placeholder="示例:
技术,100
创新,80
发展,60" 
        />
      </a-form-item>
      
      <a-button type="primary" @click="importBatchWords" style="margin-bottom: 16px">
        导入数据
      </a-button>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';

const props = defineProps({
  options: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['update:options']);

// 本地存储options，用于编辑
const localOptions = ref<any>({
  title: {
    text: '词云图'
  },
  series: [{
    type: 'wordCloud',
    shape: 'circle',
    sizeRange: [12, 60],
    rotationRange: [-45, 45],
    rotationStep: 15,
    gridSize: 8,
    drawOutOfBound: false,
    textStyle: {
      fontFamily: 'sans-serif',
      fontWeight: 'bold',
      fontSize: [12, 60],
      color: function () {
        return 'rgb(' + [
          Math.round(Math.random() * 160),
          Math.round(Math.random() * 160),
          Math.round(Math.random() * 160)
        ].join(',') + ')';
      }
    },
    emphasis: {
      textStyle: {
        shadowBlur: 10,
        shadowColor: '#333'
      }
    },
    data: [
      { name: '词云', value: 100 },
      { name: '可视化', value: 80 },
      { name: '数据', value: 70 },
      { name: '分析', value: 60 },
      { name: '图表', value: 50 }
    ]
  }]
});

// 词云数据
const wordCloudData = ref<any[]>([]);

// 形状
const cloudShape = ref('circle');

// 旋转
const rotationEnabled = ref(true);
const rotationRange = ref<[number, number]>([-45, 45]);

// 颜色方案
const colorScheme = ref('random');
const startColor = ref('#c6e48b');
const endColor = ref('#196127');

// 批量导入文本
const batchWordsText = ref('');

// 更新词云形状
const updateCloudShape = (shape: string) => {
  localOptions.value.series[0].shape = shape;
  emitUpdate();
};

// 更新旋转设置
const updateRotation = (enabled: boolean) => {
  rotationEnabled.value = enabled;
  
  if (enabled) {
    localOptions.value.series[0].rotationRange = rotationRange.value;
  } else {
    localOptions.value.series[0].rotationRange = [0, 0];
  }
  
  emitUpdate();
};

// 更新旋转角度范围
const updateRotationRange = (range: [number, number]) => {
  localOptions.value.series[0].rotationRange = range;
  emitUpdate();
};

// 更新颜色方案
const updateColorScheme = (scheme: string) => {
  colorScheme.value = scheme;
  
  switch (scheme) {
    case 'category':
      localOptions.value.series[0].textStyle.color = function () {
        // 使用ECharts内置的分类颜色
        const colors = [
          '#5470c6', '#91cc75', '#fac858', '#ee6666',
          '#73c0de', '#3ba272', '#fc8452', '#9a60b4'
        ];
        return colors[Math.floor(Math.random() * colors.length)];
      };
      break;
    case 'random':
      localOptions.value.series[0].textStyle.color = function () {
        return 'rgb(' + [
          Math.round(Math.random() * 160),
          Math.round(Math.random() * 160),
          Math.round(Math.random() * 160)
        ].join(',') + ')';
      };
      break;
    case 'gradient':
      updateGradientColors();
      break;
  }
  
  emitUpdate();
};

// 更新渐变颜色
const updateGradientColors = () => {
  // 注意：这里设置的是函数字符串，真正的函数会在ECharts初始化时生效
  localOptions.value.series[0].textStyle.color = `function (_, index) {
    const startColorRGB = hexToRgb('${startColor.value}');
    const endColorRGB = hexToRgb('${endColor.value}');
    const total = ${wordCloudData.value.length || 10};
    const ratio = index / total;
    
    return 'rgb(' + [
      Math.round(startColorRGB[0] + (endColorRGB[0] - startColorRGB[0]) * ratio),
      Math.round(startColorRGB[1] + (endColorRGB[1] - startColorRGB[1]) * ratio),
      Math.round(startColorRGB[2] + (endColorRGB[2] - startColorRGB[2]) * ratio)
    ].join(',') + ')';
  }`;
  
  emitUpdate();
};

// 添加词语
const addWord = () => {
  wordCloudData.value.push({
    name: '新词语',
    value: 50
  });
  
  updateWordCloudData();
};

// 移除词语
const removeWord = (index: number) => {
  wordCloudData.value.splice(index, 1);
  updateWordCloudData();
};

// 更新词云数据到options
const updateWordCloudData = () => {
  localOptions.value.series[0].data = [...wordCloudData.value];
  emitUpdate();
};

// 批量导入词语
const importBatchWords = () => {
  const lines = batchWordsText.value.split('\n').filter(line => line.trim());
  const newWords = [];
  
  for (const line of lines) {
    const parts = line.split(',');
    if (parts.length >= 2) {
      const name = parts[0].trim();
      const value = parseInt(parts[1].trim(), 10);
      
      if (name && !isNaN(value)) {
        newWords.push({ name, value });
      }
    }
  }
  
  if (newWords.length > 0) {
    wordCloudData.value = newWords;
    updateWordCloudData();
    batchWordsText.value = ''; // 清空输入
  }
};

// 向父组件发送更新的options
const emitUpdate = () => {
  emit('update:options', { ...localOptions.value });
};

// 初始化
onMounted(() => {
  // 深拷贝props的options
  if (props.options) {
    localOptions.value = JSON.parse(JSON.stringify(props.options));
    
    // 确保必要的属性存在
    if (!localOptions.value.title) {
      localOptions.value.title = { text: '词云图' };
    }
    
    if (!localOptions.value.series || !localOptions.value.series.length) {
      localOptions.value.series = [{
        type: 'wordCloud',
        shape: 'circle',
        sizeRange: [12, 60],
        rotationRange: [-45, 45],
        textStyle: {
          fontFamily: 'sans-serif',
          fontWeight: 'bold',
          fontSize: [12, 60],
          color: function () {
            return 'rgb(' + [
              Math.round(Math.random() * 160),
              Math.round(Math.random() * 160),
              Math.round(Math.random() * 160)
            ].join(',') + ')';
          }
        },
        data: []
      }];
    }
    
    // 确保类型为词云图
    if (localOptions.value.series[0] && localOptions.value.series[0].type !== 'wordCloud') {
      localOptions.value.series[0].type = 'wordCloud';
    }
    
    // 初始化形状设置
    cloudShape.value = localOptions.value.series[0].shape || 'circle';
    
    // 初始化旋转设置
    const rotRange = localOptions.value.series[0].rotationRange || [-45, 45];
    rotationEnabled.value = !(rotRange[0] === 0 && rotRange[1] === 0);
    rotationRange.value = rotationEnabled.value ? rotRange : [-45, 45];
    
    // 初始化词云数据
    wordCloudData.value = localOptions.value.series[0].data || [];
  }
});

// 监听props.options变化
watch(() => props.options, (newOptions) => {
  if (newOptions) {
    localOptions.value = JSON.parse(JSON.stringify(newOptions));
    
    // 更新词云数据
    wordCloudData.value = localOptions.value.series[0].data || [];
  }
}, { deep: true });
</script>

<style scoped>
.chart-settings-container {
  padding: 16px;
}

.word-item {
  padding: 10px;
  margin-bottom: 12px;
  border: 1px dashed #ddd;
  border-radius: 4px;
}

.delete-btn-container {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  height: 100%;
}
</style> 